import { Router } from 'express'

const router = Router()

// 内存模拟角色数据
let roles = [
  { id: 1, name: '管理员', description: '系统管理员', status: 1 }
]

// 获取角色列表（支持分页和名称筛选）
router.get('/', (req, res) => {
  let { page = 1, limit = 10, name = '' } = req.query
  page = Math.max(Number(page) || 1, 1)
  limit = Math.max(Number(limit) || 10, 1)
  name = String(name || '')

  let filtered = Array.isArray(roles)
    ? roles.filter(r => r.name.includes(name))
    : []
  const start = (page - 1) * limit
  const end = start + limit
  res.json({
    code: 0,
    message: 'success',
    total: filtered.length,
    items: filtered.slice(start, end)
  })
})

// 新增角色
router.post('/', (req, res) => {
  const { name, description = '', status = 1 } = req.body
  if (!name) {
    return res.status(400).json({ code: 1, message: '角色名称不能为空' })
  }
  const id = roles.length ? (roles[roles.length - 1]?.id ?? 0) + 1 : 1
  const newRole = { id, name, description, status }
  roles.push(newRole)
  return res.json({ code: 0, message: '新增成功', item: newRole })
})

// 更新角色
router.put('/:id', (req, res) => {
  const idx = roles.findIndex(r => r.id === Number(req.params.id))
  if (idx !== -1) {
    roles[idx] = { ...roles[idx], ...req.body }
    return res.json({ code: 0, message: '更新成功', item: roles[idx] })
  } else {
    return res.status(404).json({ code: 1, message: '未找到角色' })
  }
})

// 删除角色
router.delete('/:id', (req, res) => {
  const idx = roles.findIndex(r => r.id === Number(req.params.id))
  if (idx !== -1) {
    roles.splice(idx, 1)
    return res.json({ code: 0, message: '删除成功' })
  } else {
    return res.status(404).json({ code: 1, message: '未找到角色' })
  }
})

export default router 